import { camelCase } from 'lodash'
import { useLocalStorage } from '@vueuse/core'
import { getUserInfo, userLogin } from '@/api/user.js'
import { dynamicRoutes } from '@/router/index.js'

export const useAuthStore = defineStore(
  'auth',
  () => {
    // 布局根路由名称
    const layoutRouteName = import.meta.env.VITE_LAYOUT_ROUTE_NAME
    const router = useRouter()
    const route = useRoute()

    // 菜单树形结构
    const treeMenus = ref([])
    // 当前用户的所有菜单
    const menus = ref([])
    // 当前所有菜单，id为key,value为menu
    const menusObj = ref({})
    // 登录状态 success, failed
    const loginStatus = ref()
    // 路由白名单，可以直接跳转
    const whiteList = ['']
    // 当前登录的token ，持久化到本地储存
    const token = ref('')
    //当前登录的用户信息
    const userInfo = ref({})
    //当前用户拥有的角色
    const orgRoles = ref([])
    // 获取当前用户菜单首个路由
    function getFirstRoute() {
      const arr = [...treeMenus.value]
      while (arr.length) {
        const menu = arr.shift()
        if (!menu) return
        if (menu.type === 'menu') return menu
        if (menu.children?.length) {
          arr.unshift(...menu.children)
        }
      }
    }

    // 初始化动态菜单
    function initMenu() {
      menusObj.value = {}
      menus.value.forEach((i) => {
        i.children = []
        menusObj.value[i.id] = i
      })

      // 转为树形结构
      treeMenus.value = menus.value.filter((i) => {
        const parent = menusObj.value[i.parentId]
        if (parent) {
          parent.children.push(i)
          return false
        }
        return true
      })
      console.log('initMenu', menusObj.value, menus.value, treeMenus.value)
      initDynamicRouter()
    }

    // 初始化动态路由
    function initDynamicRouter() {
      const viewsComponent = import.meta.glob('@/views/**/*.vue')
      router.addRoute({
        name: layoutRouteName,
        path: `/${layoutRouteName}`,
        component: () => import('@/layout/Basic/index.vue'),
      })
      menus.value.forEach((i) => {
        // 路由路径
        const path = getMenuLevelArr(i.id)
          .map((i) => i.path)
          .join('/')
        // 路由全路径
        const fullPath = `/${layoutRouteName}/${path}`
        i.fullPath = fullPath
        if (i.type === 'menu' && ['route', 'iframe'].includes(i.handleType)) {
          // 路由名称
          const name = getMenuLevelArr(i.id)
            .map((i) => i.name)
            .join('/')
          // 组件name
          const componentName = camelCase(fullPath)
          const dynamicRoute = {
            name,
            path,
            fullPath,
            component: async () => {
              const component = viewsComponent[i.component]
              if (!component) throw new Error(`${i.component} 文件不存在！`)
              return component().then((comp) => ({
                ...comp.default,
                name: componentName,
              }))
            },
            meta: {
              title: i.title,
              cache: i.cache,
              component: i.component,
              icon: i.icon,
              componentName,
            },
          }
          i.componentName = componentName
          router.addRoute(layoutRouteName, dynamicRoute)
        }
      })
    }

    // 获取菜单id的层级数组
    function getMenuLevelArr(id) {
      const arr = []
      let currentMenu = menusObj.value[id]
      while (currentMenu) {
        arr.unshift(currentMenu)
        currentMenu = menusObj.value[currentMenu.parentId]
      }
      return arr
    }

    // 路由前置守卫，自动登录
    async function beforeEach(to) {
      // 白名单直接跳转
      if (whiteList.includes(to.fullPath)) {
        return
      }
      let path
      if (token.value && !loginStatus.value) {
        // 初始化登录逻辑
        loginStatus.value = 'success' // 登录成功
        menus.value = dynamicRoutes
        initMenu()
        return to.fullPath
      }
      // 如果是登录失败的，直接跳转到登录页
      if (loginStatus.value !== 'success') {
        path = '/login'
      } else {
        // 如果是登录成功的，并且路由是根路径或者登录页的，跳转到菜单第一个路由
        if (['/', '/login'].includes(to.fullPath)) {
          path = getFirstRoute()?.fullPath
        } else {
          return path
        }
      }
      // 重定向路由和原跳转路由路径相同，则无需处理
      if (to.fullPath !== path) {
        return path
      }
    }

    // 设置token
    function setToken(val) {
      token.value = val
    }

    // 设置登录用户信息
    function setLoginUserInfo(loginUserInfo) {
      console.log('setLoginUserInfo', loginUserInfo)

      loginStatus.value = 'success' // 登录成功
      setToken(loginUserInfo.token.accessToken)
      getUserInfo({ username: loginUserInfo.name }).then((res) => {
        userInfo.value = res.data
      })
      menus.value = loginUserInfo.menus
      initMenu()
    }

    return {
      userInfo,
      token,
      menus,
      treeMenus,
      loginStatus,
      setToken,
      beforeEach,
      getFirstRoute,
      setLoginUserInfo,
    }
  },
  {
    persist: {
      enabled: true,
      strategies: [
        {
          storage: sessionStorage,
          paths: ['userInfo', 'token'],
        },
      ],
    },
  },
)
